<template>
  <view class="container">
    <!-- 顶部个人信息卡片 -->
    <view class="profile-card">
      <view class="profile-avatar">
        <view class="avatar-upload" @click="chooseImage('avatar')">
          <view class="avatar-placeholder" v-if="!formData.avatar">
            <u-icon name="camera" size="40" color="#fff"></u-icon>
          </view>
          <image v-else :src="formData.avatar" class="avatar-image"></image>
        </view>
      </view>

      <view class="profile-info" @click="openDatePicker">
        <text class="profile-name" @click="openDatePicker">{{ info.compellation || "陈欢欢" }}</text>
        <view class="profile-details">
          <view class="detail-item">
            <text class="detail-label">性别</text>
            <text class="detail-value">{{info.sex == 1 ? "男" : "女" }}</text>
          </view>
          <!-- <view class="detail-item">
            <text class="detail-label">年龄</text>
            <text class="detail-value">{{ "18" || "--" }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">身高</text>
            <text class="detail-value">{{ "180" || "--" }}cm</text>
          </view> -->
        </view>
        <view class="date-picker" @click="openDatePicker">
          <text class="date-label">体测日期</text>
          <text class="date-value" @click="openDatePicker">
            {{ formData.recordDate || "请选择日期" }}
          </text>
        </view>
      </view>
    </view>

    <!-- 照片上传区域 -->
    <view class="photo-section">
      <view class="section-header">
        <view class="section-title">身体照片记录</view>
      </view>

      <view class="photo-grid">
        <view
          class="photo-item"
          v-for="(item, index) in photoTypes"
          :key="index"
          @click="chooseImage(item.field)"
        >
          <view class="upload-card" v-if="!formData[item.field]">
            <view class="upload-content">
              <u-icon name="camera-fill" color="#666" size="44"></u-icon>
              <text class="upload-title">{{ item.text }}</text>
              <text class="upload-desc">点击上传</text>
            </view>
          </view>
          <image v-else :src="formData[item.field]" class="preview-image" mode="widthFix"></image>
        </view>
      </view>
    </view>

    <!-- 数据记录区域 -->
    <view class="data-section">
      <view class="section-title">身体数据记录</view>
      <view class="data-grid">
        <view class="data-card" v-for="(item, index) in formData.fitness" :key="index">
          <view class="data-input">
            <u--input
              v-model="item.value"
              placeholder="请输入"
              border="none"
              @change="handleDataChange(item.field, $event)"
            ></u--input>
          </view>
          <text class="data-label">{{ item.label }}</text>
          <text class="data-unit">{{ item.unit }}</text>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="submit-section">
      <button class="submit-btn" @click="submit(3)">
        <text class="btn-text">保存数据</text>
      </button>
    </view>

    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="show"
      v-model="value1"
      mode="date"
      @close="show = false"
      @cancel="show = false"
      @confirm="confirm"
    ></u-datetime-picker>
  </view>
</template>
<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

import { getDetail, customerDetail, updatefitness, uploadFile } from "../../api/fit";
export default {
  name: "",
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    return {
      show: false,
      value1: "", // 记录日期
      formData: {
        customerId: '',
        avatar: "",
        frontPic: "",
        flankPic: "",
        backPic: "",
        fitness: [], // 改为数组格式
        recordDate: "",
      },
      // 照片类型定义
      photoTypes: [
        {
          text: "正面照片",
          field: "frontPic",
          desc: "正面站姿",
          icon: "camera",
        },
        {
          text: "侧面照片",
          field: "flankPic",
          desc: "侧面站姿",
          icon: "camera",
        },
        {
          text: "背面照片",
          field: "backPic",
          desc: "背面站姿",
          icon: "camera",
        },
      ],
      // 身体数据项定义
      dataItems: [
        { label: "体重", field: "weight", unit: "kg" },
        { label: "体脂率", field: "fat", unit: "%" },
        { label: "BMI", field: "bmi", unit: "" },
        { label: "基础代谢", field: "metabolism", unit: "kcal" },
        { label: "肌肉量", field: "slm", unit: "kg" },
        { label: "腰臀比", field: "whr", unit: "" },
        { label: "胸围", field: "bust", unit: "cm" },
        { label: "腰围", field: "waist", unit: "cm" },
        { label: "臀围", field: "hipline", unit: "cm" },
      ],
      info:{},
    };
  },
  created() {},
  mounted() {},
  onLoad(e) {
    console.log(e,'eeeeee');
    
    this.formData.customerId = e.id;
    this.getInfo()
    this.getDetail(e.customerId)
  },
  methods: {
    async getDetail(id){
      const res = await getDetail(id)
      console.log(res,'asdasdasdas');
      
      if (res.data && res.data.fitness) {
        // 将对象格式转换为数组格式
        const fitnessData = res.data.fitness;
        const fitnessArray = Object.keys(fitnessData).map(key => ({
          field: key,
          label: fitnessData[key].label,
          value: fitnessData[key].value,
          unit: this.dataItems.find(item => item.field === key)?.unit || ''
        }));

        this.formData = {
          ...this.formData,
          ...res.data,
          fitness: fitnessArray
        };
      }
      console.log(this.formData,'this.formData');
      
      this.$forceUpdate(); // 强制更新视图
    },
    async getInfo(){
      const res = await customerDetail(this.formData.customerId);
      console.log(res,'asdasdasdas');
      
      this.info = res.data;
      this.$forceUpdate(); // 强制更新视图
    },
    openDatePicker() {
      console.log("openDatePicker called"); // 添加日志
      this.show = true;
    },

    // 确认日期选择
    confirmDate(e) {
      // 格式化日期
      const date = new Date(e);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      this.formData.recordDate = `${year}-${month}-${day}`;
      console.log(this.formData.recordDate,'this.formData.recordDate');
      this.show = false;
    },

    // 取消日期选择
    cancelDate() {
      this.show = false;
    },
    // 处理日期选择确认
    async confirm(e) {
      const timeFormat = uni.$u.timeFormat;
      this.value1 = timeFormat(e.value, "yyyy-mm-dd");
      this.formData.recordDate = this.value1;
      this.show = false;
    },

    // 处理数据输入变化
    handleDataChange(field, value) {
      const fitnessItem = this.formData.fitness.find(item => item.field === field);
      if (fitnessItem) {
        fitnessItem.value = value;
      }
    },

    // 选择图片
    chooseImage(field) {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.uploadImage(tempFilePath, field);
        },
        fail: (err) => {
          console.error("选择图片失败:", err);
        }
      });
    },

    // 上传图片
    async uploadImage(filePath, field) {
      try {
        uni.showLoading({
          title: "上传中..."
        });

        const res = await uploadFile(filePath);
        
        if (res.code === 200) {
          this.formData[field] = 'https://api.itaster.cn/file/' + res.message; // 设置返回的图片URL，并拼接前缀
          uni.showToast({
            title: "上传成功",
            icon: "success"
          });
        } else {
          throw new Error(res.msg || "上传失败");
        }
        
      } catch (error) {
        console.error("上传错误:", error);
        uni.showToast({
          title: "上传失败",
          icon: "none"
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 删除图片
    deletePic(event, field) {
      this.formData[field] = "";
    },

    // 提交表单
    async submit() {
      try {
        // 在提交前将数组格式转换回对象格式
        const submitData = {
          ...this.formData,
          fitness: this.formData.fitness.reduce((obj, item) => {
            obj[item.field] = {
              label: item.label,
              value: item.value
            };
            return obj;
          }, {})
        };

        const res = await updatefitness(submitData);
        
        if (res.code === 200) {
          uni.showToast({
            title: "保存成功",
            icon: "success",
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      } catch (error) {
        console.error(error);
        uni.showToast({
          title: "保存失败",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding: 30rpx;
}

// 个人信息卡片
.profile-card {
  position: relative;
  display: flex;
  padding: 40rpx;
  background: #000;
  border-radius: 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  margin-bottom: 40rpx;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: linear-gradient(45deg, rgba(255, 255, 255, 0.1), transparent);
  }
}

.profile-avatar {
  width: 180rpx;
  height: 180rpx;
  margin-right: 40rpx;

  .avatar-upload {
    width: 100%;
    height: 100%;
  }

  .avatar-placeholder {
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
    }
  }

  .avatar-image {
    width: 100%;
    height: 100%;
    border-radius: 20rpx;
    object-fit: cover;
  }
}

.profile-info {
  flex: 1;
  color: #fff;
}

.profile-name {
  font-size: 40rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
}

.profile-details {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 10rpx;

  .detail-label {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.6);
  }

  .detail-value {
    font-size: 28rpx;
  }
}

.date-picker {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 12rpx 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12rpx;
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    background: rgba(255, 255, 255, 0.15);
  }

  .date-label {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.6);
  }

  .date-value {
    font-size: 28rpx;
  }
}

// 照片上传区域
.photo-section {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);

  .section-header {
    padding: 0 10rpx;
    margin-bottom: 30rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24rpx;
  padding: 0 10rpx;
}

.photo-item {
  position: relative;
  width: 100%;
  aspect-ratio: 3/4;
  border-radius: 16rpx;
  overflow: hidden;
  background: #f8f8f8;
}

.upload-card {
  width: 100%;
  height: 100%;
  background: #f8f8f8;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &:active {
    background: #f0f0f0;
  }

  .upload-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
  }

  .upload-title {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    text-align: center;
  }

  .upload-desc {
    font-size: 24rpx;
    color: #999;
    text-align: center;
  }
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 16rpx;
}

// 数据记录区域
.data-section {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.data-card {
  position: relative;
  padding: 30rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
  }

  .data-input {
    margin-bottom: 16rpx;

    ::v-deep .u-input {
      background: transparent;
      font-size: 32rpx;
      font-weight: 500;
    }
  }

  .data-label {
    font-size: 26rpx;
    color: #666;
  }

  .data-unit {
    position: absolute;
    right: 30rpx;
    bottom: 30rpx;
    font-size: 24rpx;
    color: #999;
  }
}

// 提交按钮
.submit-section {
  padding: 20rpx 40rpx 60rpx;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  background: #000;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  transform: translateY(0);
  transition: all 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
  }

  .btn-text {
    color: #fff;
    font-size: 32rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
  }
}

// 修复上传组件样式
::v-deep .u-upload {
  &__button {
    width: 100% !important;
    height: 100% !important;
  }

  &__wrap {
    width: 100% !important;
    height: 100% !important;
  }

  &__preview-wrap {
    border-radius: 16rpx;
    overflow: hidden;
  }
}

.profile-card {
  position: relative;
  display: flex;
  padding: 40rpx;
  background: #000;
  border-radius: 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  margin-bottom: 40rpx;
  z-index: 1; // 确保卡片在正确的层级
}

.profile-info {
  flex: 1;
  position: relative;
  z-index: 2; // 确保信息在正确的层级
}

// 新增包装器确保点击区域正确
.date-picker-wrapper {
  position: relative;
  z-index: 3;
  margin-top: 20rpx;
}

.date-picker {
  position: relative;
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 12rpx 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12rpx;
  z-index: 3;

  // 移除可能影响点击的属性
  pointer-events: auto;

  &:active {
    opacity: 0.8;
    background: rgba(255, 255, 255, 0.2);
  }
}

.date-label {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
}

.date-value {
  font-size: 28rpx;
  color: #ffffff;
}

// 确保没有其他元素覆盖
.profile-card::before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(45deg, rgba(255, 255, 255, 0.1), transparent);
  z-index: 1;
  pointer-events: none; // 确保不影响点击
}
</style>
